package com.ustb.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ustb.springboot.common.utils.R;
import com.ustb.springboot.common.utils.TokenUtil;
import com.ustb.springboot.dao.AnswerDatetimeDao;
import com.ustb.springboot.entity.*;
import com.ustb.springboot.service.OptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.ustb.springboot.dao.AnswerListboxDao;
import com.ustb.springboot.service.AnswerListboxService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Service("answerListboxService")
public class AnswerListboxServiceImpl extends ServiceImpl<AnswerListboxDao, AnswerListboxEntity> implements AnswerListboxService {
    @Resource
    private AnswerListboxDao answerListboxDao;
    @Autowired
    private OptionService optionService;
    @Override
    public R save(HttpServletRequest request, AnswerListboxEntity answerListbox) {
        answerListbox.setUserId(TokenUtil.getId(request));

        return this.saveOrUpdate(answerListbox) ? R.ok(20000, "保存答案成功") : R.error(2000, "保存答案失败");
    }

    @Override
    public List<AnswerListboxEntity> queryAnsListboxWithQuestionId(String Question_id) {
        QueryWrapper<AnswerListboxEntity> answerListboxEntityQueryWrapper = new QueryWrapper<>();
        answerListboxEntityQueryWrapper.eq("question_id",Question_id);
        List<AnswerListboxEntity> answerListboxEntityList = answerListboxDao.selectList(answerListboxEntityQueryWrapper);
        return  answerListboxEntityList;
    }

    @Override
    public  Map<String, Object> summerizeListBoxMessages(Map<String, Object> body) {
        List<AnswerListboxEntity> answerListboxEntityList = new ArrayList<>();
        answerListboxEntityList = queryAnsListboxWithQuestionId(body.get("question_id").toString());
        //查询到的checkbox列表
        Map<String ,Object> summerizeMessages = new HashMap<>();
        Map <String,Map>TempSummerizeMessage = new HashMap<>();
        //汇总信息的列表
        Integer sum = 0;
        //计算所有的选择次数（用于计算百分比）
        List<OptionEntity> optionEntityList= optionService.queryWithId(body);
        sortByOrderId(optionEntityList,0,optionEntityList.size()-1);
        //System.out.println(optionEntityList);
        //获取选项信息
        List<String> Message = new ArrayList<>();
        for(OptionEntity optionEntity : optionEntityList){
            Message.add(optionEntity.getOrderId().toString());
            if (optionEntity.getContent().isEmpty() == false)
                Message.add(optionEntity.getContent());
            else
                Message.add("null");
            Message.add("0");
            Message.add("0");
        }
        //System.out.println(Message);
        System.out.println(answerListboxEntityList);
        for(AnswerListboxEntity answerListboxEntity : answerListboxEntityList){
            Integer num = Integer.parseInt(answerListboxEntity.getOptionId().toString());
            //System.out.println("num:"+num.toString());
            Integer index = (num - 1) * 4 + 2;
            Integer newVal = Integer.parseInt(Message.get(index).toString()) + 1;
            Message.set(index,newVal.toString());
            sum++;
        }
        System.out.println("answerListboxEntityList"+answerListboxEntityList.size());
        for (Integer i = 1 ; i < answerListboxEntityList.size()  ; i++){
            Integer index = (i - 1)*4 + 2;
            Integer num = Integer.parseInt(Message.get(index).toString());
            Float target = (num.floatValue()/sum.floatValue())*100;
            String Target = target.toString();
            Message.set(index + 1,Target);
        }
        //List<List<String>> structMessage = new ArrayList<>();

        //封装
        List<Map> structMessage = new ArrayList<>();

        for(int i = 0; i < Message.size() / 4 ; i++){
            Map<String,String> struct = new HashMap<>();
            struct.put("order_id",Message.get(i * 4 + 0));
            struct.put("order_information",Message.get(i * 4 + 1));
            struct.put("number",Message.get(i * 4 + 2));
            struct.put("percentage",Message.get(i * 4 + 3));
//            for(int j = 0; j < 4 ; j++){
//                struct.add(Message.get(i * 4 + j));
//            }
            structMessage.add(struct);
        }
        summerizeMessages.put("total_message",structMessage);
        summerizeMessages.put("sum",sum);
        return summerizeMessages;
    }

    @Override
    public R delete(Map<String, Object> body) {
        QueryWrapper<AnswerListboxEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", body.get("id"));
        return answerListboxDao.delete(queryWrapper) == 1 ? R.ok(20000, "删除成功！") : R.error(2000, "删除失败");
    }
    private  void sortByOrderId(List<OptionEntity> list,Integer start,Integer end){
        if (start >= end) {
            return;
        }
        OptionEntity a =list.get(start);//定义基准值
        int i = start;//开始位置下标
        int j = end;//末尾位置下标
        while (i < j) {
            while (i<j && Integer.parseInt(list.get(j).getOrderId().toString())>=a.getOrderId()) {
                j--;
            }
            while (i<j && Integer.parseInt(list.get(i).getOrderId().toString())<=a.getOrderId()) {
                i++;
            }
            if (i<j) {//交换i和j的值
                Collections.swap(list,i,j);
            }
        }
        list.set(start,list.get(i));
        list.set(i,a);
        sortByOrderId(list, start, i-1);//递归调用
        sortByOrderId(list, i+1, end);
    }
}